using System;
using System.Collections.Generic;
using MSOffice = Microsoft.Office.Core;
using MSOutlook = Microsoft.Office.Interop.Outlook;

namespace Microsoft.Sample.Outlook.Utility
{



    public sealed class ToolbarButton : ToolbarControl
	{
		private MSOffice.MsoButtonStyle _style = MSOffice.MsoButtonStyle.msoButtonCaption;

		public event EventHandler<CommandBarEventArgs> Click;

		public MSOffice.MsoButtonStyle Style
		{
			get { return _style; }
			set { _style = value; }
		}

		public ToolbarButton(string ID)
			: base(ID)
		{
		}

		public ToolbarButton(string ID, string caption)
			: base(ID, caption)
		{
		}

		public ToolbarButton(string ID, string caption, string tooltip)
			: base(ID, caption, tooltip)
		{
		}

		public ToolbarButton(string ID, string caption, MSOffice.MsoButtonStyle style)
			: base(ID, caption)
		{
			_style = style;
		}

		public ToolbarButton(string ID, string caption, string tooltip, MSOffice.MsoButtonStyle style)
			: base(ID, caption, tooltip)
		{
			_style = style;
		}

		internal override void Attach(MSOffice.CommandBar bar, WindowAdapter window)
		{
			MSOffice.CommandBarButton btn = FindControl<MSOffice.CommandBarButton>(bar);

			if (btn == null)
			{
				btn = (MSOffice.CommandBarButton)bar.Controls.Add(
					MSOffice.MsoControlType.msoControlButton,
					Type.Missing, Type.Missing,
					this.Position != null ? this.Position.Value : Type.Missing, true);

				btn.Parameter = this.ID;
				btn.Tag = Guid.NewGuid().ToString();
			}

			btn.Caption = this.Caption;
			btn.TooltipText = this.ToolTip;
			btn.Style = this.Style;

			btn.Click += delegate(MSOffice.CommandBarButton Ctrl, ref bool CancelDefault)
			{
				CommandBarEventArgs args = new CommandBarEventArgs(window, bar);
                //Use CommandBarManager's DynamicInvoke to ensure this event fires on the right thread
                CommandBarManager.DynamicInvoke(Click, this, args);
			};

			AddControl((MSOffice.CommandBarControl)btn);
			window.Close += delegate(object sender, EventArgs args)
			{
				RemoveControl((MSOffice.CommandBarControl)btn);
			};
		}
	}
}
